package com.superiron.scaffold.websocket;

import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.nio.charset.Charset;
import java.util.Map;

/**
 * Describes: WebSocket握手拦截器
 * Auth: yzg
 */
@Slf4j
public class MyHandshakeInterceptor implements HandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> attributes) throws Exception {
        log.info("握手开始");
        // 获得请求参数
        Map<String, String> paramMap = HttpUtil.decodeParamMap(request.getURI().getQuery(), Charset.defaultCharset());
        String appId = paramMap.get("APPID");
        String organId = paramMap.get("ORGANID");
        if (StringUtils.isNotBlank(appId) && StringUtils.isNotBlank(organId)) {
            // 放入属性域
            attributes.put("appId", appId);
            attributes.put("organId", organId);
            log.info("租户：{}握手成功！", organId);
            return true;
        }
        return false;
    }

    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {
        log.info("================After Handshake================");
        if (e != null) {
            log.error("握手失败：{},{}", "After Handshake", e);
        }
        log.info("握手完成");
    }

}

